import store from '../store'

const uuid = require('uuid/v4')
const webSqlUtil = require('./webSqlUtil')

let isDropTable = false

/**
 * 创建消息表
 * msgid
 * msg
 * msgtype
 * createtime
 * fsuserid
 * jsuserid
 * @returns {Promise<any>}
 */
export function createTable () {
  return webSqlUtil.run(`create table if not exists message(
      msgid text, 
      msg text,
      msgtype text,
      createtime number,
      relationuserip text,
      type text
    )`)
}

export function dropTable () {
  return webSqlUtil.run(`drop table if exists message`)
}

export async function initTable () {
  if (isDropTable) {
    isDropTable = false
    await dropTable()
  }
  return createTable()
}

// 增加消息
export async function addMsg ({msgid = uuid(), msg, relationuserip, msgtype, createtime = Date.now(), type}) {
  await initTable()
  return webSqlUtil.run(`insert into message(msgid,msg,msgtype,createtime,relationuserip,type)
  values (?,?,?,?,?,?)`, [msgid, msg, msgtype, createtime, relationuserip, type])
}

// 删除消息

// 修改消息

// 查询消息
export async function getMsgs () {
  await initTable()
  return webSqlUtil.run(`select * from message order by createtime`, [])
}

export async function getMsgsByIp (relationuserip) {
  await initTable()
  return webSqlUtil.run(`select * from message where relationuserip=?`, [relationuserip])
}

export async function getHistorySessionList () {
  await initTable()
  let historySessionList = await webSqlUtil.run(`select
         msg,xm,relationuserip,tx,zt,dnm,max(createtime) createtime 
         from (select 
         m.*,u.xm,u.dnm,u.tx,u.zt 
         from message m left join user u on u.userip=m.relationuserip) group by relationuserip order by createtime`)
  store.dispatch('setHistorySessionList', historySessionList)
}
